package com.zby.service.imp;

import com.zby.common.minio.MinioFuntion;
import com.zby.common.minio.MinioPojo;
import com.zby.service.UploadFileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author wuyanzhu
 */
@Service
public class UploadFileServiceImp implements UploadFileService {
    private static final String BUCKET_KEY = "temporary";

    @Autowired
    private MinioPojo minioPojo;
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioFuntion minioFuntion;

    @Override
    public String uploadFileImg(MultipartFile file) {
//        临时上传图片操作
        if (file.isEmpty()) {
            throw new RuntimeException("文件为空");
        }
        try {

            minioFuntion.ensureBucketExists(BUCKET_KEY);

//        设置文件名
            String fileName = UUID.randomUUID() + "-" + file.getOriginalFilename();
//        上传文件
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(minioFuntion.getBucketName(BUCKET_KEY))
                            .object(fileName)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            return String.join("/",
                    minioPojo.getEndpoint(),
                    minioFuntion.getBucketName(BUCKET_KEY),
                    fileName
            );

        } catch (Exception e) {
            e.printStackTrace();
            return "图片上传失败";
        }
    }


}






